package com.macro.mall.tiny.modules.oms.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.tiny.common.api.CommonResult;
import com.macro.mall.tiny.common.api.CommonPage;
import com.macro.mall.tiny.modules.oms.dto.OrderCreateParam;
import com.macro.mall.tiny.modules.oms.vo.OrderListVO;
import com.macro.mall.tiny.modules.oms.dto.OrderQueryParam;
import com.macro.mall.tiny.modules.oms.dto.OrderUpdateAmountParam;
import com.macro.mall.tiny.modules.oms.dto.OrderUpdateStatusParam;
import com.macro.mall.tiny.modules.oms.model.Order;
import com.macro.mall.tiny.modules.oms.model.OrderGoods;
import com.macro.mall.tiny.modules.oms.model.OrderLog;
import com.macro.mall.tiny.modules.oms.model.User;
import com.macro.mall.tiny.modules.oms.service.OrderService;
import com.macro.mall.tiny.modules.oms.service.UserService;
import com.macro.mall.tiny.security.util.JwtTokenUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@Tag(name = "OrderController", description = "订单管理")
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Operation(summary = "创建订单")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<Object> createOrder(@RequestBody OrderCreateParam orderCreateParam) {
        try {
            String orderNo = orderService.createOrder(orderCreateParam);
            if (orderNo != null) {
                java.util.Map<String, Object> result = new java.util.HashMap<>();
                result.put("orderNo", orderNo);
                return CommonResult.success(result, "下单成功");
            } else {
                return CommonResult.failed("下单失败");
            }
        } catch (Exception e) {
            return CommonResult.failed("下单失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取订单列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<Order>> getOrderList(OrderQueryParam queryParam) {

        // 从token中解析用户ID，如果queryParam中没有提供userId
        if (queryParam.getUserId() == null && queryParam.getToken() != null) {
            try {
                String userIdStr = jwtTokenUtil.getUserNameFromToken(queryParam.getToken());
                if (userIdStr != null && !userIdStr.isEmpty()) {
                    queryParam.setUserId(Integer.parseInt(userIdStr));
                }
            } catch (Exception e) {
                return CommonResult.failed("无效的token");
            }
        }

        if (queryParam.getUserId() == null && queryParam.getUserName() != null) {
            // 需要实现从用户表根据userName查询userId的逻辑
             User user = userService.getByName(queryParam.getUserName());
             if (user != null) {
                 queryParam.setUserId(user.getUserId());
             }
        }

        List<Order> orderList = orderService.getOrderList(queryParam);
        return CommonResult.success(orderList);
    }

    @Operation(summary = "获取用户端订单列表")
    @RequestMapping(value = "/user/list", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<CommonPage<OrderListVO>> getUserOrderList(OrderQueryParam queryParam) {
        try {
            // 从token中解析用户ID，如果queryParam中没有提供有效的userId
            if ((queryParam.getUserId() == null || queryParam.getUserId() == 0) && queryParam.getToken() != null) {
                try {
                    String userIdStr = jwtTokenUtil.getUserNameFromToken(queryParam.getToken());
                    if (userIdStr != null && !userIdStr.isEmpty()) {
                        queryParam.setUserId(Integer.parseInt(userIdStr));
                    }
                } catch (Exception e) {
                    return CommonResult.failed("无效的token");
                }
            }

            // 确保userId已提供且有效
            if (queryParam.getUserId() == null || queryParam.getUserId() == 0) {
                return CommonResult.failed("用户ID不能为空");
            }

            Page<OrderListVO> orderList = orderService.getUserOrderList(queryParam);
            return CommonResult.success(CommonPage.restPage(orderList));
        } catch (Exception e) {
            return CommonResult.failed("获取订单列表失败: " + e.getMessage());
        }
    }


    @Operation(summary = "获取订单详情")
    @RequestMapping(value = "/detail/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult getOrderDetail(@PathVariable String orderNo) {
        Order order = orderService.getOrderDetail(orderNo);
        if (order == null) {
            return CommonResult.failed("订单不存在");
        }

        List<OrderGoods> orderGoodsList = orderService.getOrderGoodsByOrderNo(orderNo);
//        List<OrderLog> orderLogList = orderService.getOrderLogsByOrderNo(orderNo);

        // 创建返回结果对象
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        result.put("orderInfo", order);
        result.put("orderGoodsList", orderGoodsList);
//        result.put("orderLogList", orderLogList);

        return CommonResult.success(result);
    }


    @Operation(summary = "获取订单日志列表")
    @RequestMapping(value = "/logs/{orderNo}", method = RequestMethod.GET)
    @ResponseBody
    public CommonResult<List<OrderLog>> getOrderLogs(@PathVariable String orderNo) {
        try {
            List<OrderLog> orderLogList = orderService.getOrderLogsByOrderNo(orderNo);
            return CommonResult.success(orderLogList);
        } catch (Exception e) {
            return CommonResult.failed("获取订单日志失败: " + e.getMessage());
        }
    }
    
    
    @Operation(summary = "更新订单状态")
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateOrderStatus(@RequestBody OrderUpdateStatusParam updateStatusParam) {
        try {
            boolean success = orderService.updateOrderStatus(updateStatusParam);
            if (success) {
                return CommonResult.success(null, "订单状态更新成功");
            } else {
                return CommonResult.failed("订单状态更新失败");
            }
        } catch (Exception e) {
            return CommonResult.failed("订单状态更新失败: " + e.getMessage());
        }
    }
    
    @Operation(summary = "更新订单支付金额")
    @RequestMapping(value = "/updateAmount", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult updateOrderAmount(@RequestBody OrderUpdateAmountParam updateAmountParam) {
        try {
            boolean success = orderService.updateOrderAmount(updateAmountParam);
            if (success) {
                return CommonResult.success(null, "订单金额更新成功");
            } else {
                return CommonResult.failed("订单金额更新失败");
            }
        } catch (Exception e) {
            return CommonResult.failed("订单金额更新失败: " + e.getMessage());
        }
    }

}
